<template>
	<div>
		<Form ref="brandQueryForm" :label-width="80" inline>
			<FormItem label="当前分类">
				<Cascader :data="queryCatalogData" style="width: 200px;" @on-visible-change='onVisibleChange'
				 :load-data="loadCatalogData" @on-change='onCatalogChange'>
				</Cascader>
			</FormItem>
		</Form>
		<Collapse accordion v-model="collapseValue">
			<Panel name="1">
				普通属性管理
				<div slot="content">
					<div><Button type="success" @click="onAddClick(1)">新增</Button></div>
					<Table ref="normalTable" border :columns="normalColumns" :data="normalData" @on-selection-change='onNormolChange'></Table>
				</div>
			</Panel>
			<Panel name="2">
				规格属性管理
				<div slot="content">
					<div><Button type="primary" @click="onQueryClick">查询</Button> &nbsp;
						<Button type="success" @click="onAddClick(2)">新增</Button>
					</div>
					<Table ref="specTable" border :columns="specColumns" :data="specData" @on-selection-change='onSpecChange'></Table>
				</div>
			</Panel>
		</Collapse>

		<!--新增属性对话框-->
		<Modal ref="attrModal" v-model="show" :title="modalTitle">
			<!--表单-->
			<Form ref="attrForm" :model="formData" :rules="ruleValidate" :label-width="80">
				<FormItem prop="id" style="display: none;">
					<Input v-model="formData.id"></Input>
				</FormItem>
				<FormItem label="名称" prop="name">
					<Input v-model="formData.name"></Input>
				</FormItem>
				<FormItem label="输入类型" prop="inputType">
					<Select v-model="formData.inputType">
						<Option value='1'>单选</Option>
						<Option value='2'>多选</Option>
						<Option value='3'>自定义</Option>
					</Select>
				</FormItem>
				<FormItem label="必填" prop="required">
					<Select v-model="formData.required">
						<Option value='1'>是</Option>
						<Option value='0'>否</Option>
					</Select>
				</FormItem>
				<FormItem>
					<Button type="primary" @click="handleSubmit('attrForm')" style="margin-left: 250px">确 定</Button>
					<Button @click="handleReset('attrModal')" style="margin-left: 20px">取 消</Button>
				</FormItem>
			</Form>
		</Modal>
	</div>
</template>

<script>
	import {getCatalogByPid} from '../../api/catalog.js'
	import {getAttrAndValueByCondition, addAttribute} from '../../api/attribute.js'
	import {treeToCascader} from '../../libs/object.convert.js'

	//记录当前选择的分类对象
	let catalogObjs = [];

	export default{
		data() {
			return {
				//Collapse值
				collapseValue:'1',
				//普通属性数据集
				normalData: [],
				//规格属性数据集
				specData: [],
				//普通属性
				normalColumns: [
					{
						title: '编号',
						width: 100,
						key: 'id'
					},
					{
						title: '名称',
						width: 100,
						key: 'name'
					},
					{
						title: '值',
						key: 'values'
					},
					{
						title: '操作',
						key: 'action',
						width: 300,
						align: 'center',
						render: (h, params) => {
							return h('div', [
								h('Button', {
									props: {
										type: 'warning',
										size: 'small'
									},
									on: {
										click: () => {
											console.log("属性id:" + params.row.id);
										}
									}
								}, '编辑')
							]);
						}
					}
				],
				//规格属性
				specColumns: [
					{
						title: '编号',
						width: 100,
						key: 'id'
					},
					{
						title: '名称',
						width: 100,
						key: 'name'
					},
					{
						title: '值',
						key: 'values'
					},
					{
						title: '管理属性值',
						key: 'action',
						width: 300,
						align: 'center',
						render: (h, params) => {
							return h('div', [
								h('Button', {
									props: {
										type: 'warning',
										size: 'small'
									},
									on: {
										click: () => {
											console.log("属性id:" + params.row.id);
										}
									}
								}, '编辑')
							]);
						}
					}
				],
				//查询分类数据
				queryCatalogData: [],
				//对话框是否显示
				show: false,
				//对话框标题
				modalTitle: '',
				//表单类型
				formType: 'add',
				//表单数据集
				formData: {
					id: 0,
					name: '',
					type: '',
					inputType: '',
					required: ''
				},
				//表单数据验证
				ruleValidate: {
					name: [{
							required: true,
							whitespace: true,
							message: '名称不能为空',
							trigger: 'blur'
						},
						{
							pattern: /^\S*$/,
							message: '名称不能包括空字符',
							trigger: 'blur'
						}
					],
					inputType: [{
							required: true,
							message: '输入类型不能为空',
							trigger: 'change'
						}
					],
					required: [{
						required: true,
						message: '必填不能为空',
						trigger: 'change'
					}]
				}
			}
		},
		methods: {
			//根据分类加载普通属性
			loadNormal(condition) {
				getAttrAndValueByCondition(condition).then(res => {
					this.normalData = res.data.data;
				}).catch(error => {
					console.log(error);
				})
			},
			//根据分类加载规格属性
			loadSpec(condition) {
				getAttrAndValueByCondition(condition).then(res => {
					this.specData = res.data.data;
				}).catch(error => {
					console.log(error);
				})
			},
			//级联框弹出时默认加载根分类数据
			onVisibleChange(e) {
				if (e) {
					console.log('cascader load data..............')
					//异步加载分类数据
					getCatalogByPid(0).then(res => {
						let nodes = []
						if (res.data.data) {
							nodes = treeToCascader(res.data.data);
						}
						console.log(nodes)
						this.queryCatalogData = nodes;
					}).catch(err => {
						console.log(err)
					});
				}
			},
			//加载子分类数据
			loadCatalogData(item, callback) {
				console.log('load sub catalogs..........')
				item.loading = true;
				//异步加载分类数据
					getCatalogByPid(item.value).then(res => {
						let nodes = []
						if (item.children) {
							nodes = treeToCascader(res.data.data);
							item.children = nodes;
							item.loading = false;
							callback();
						}
						console.log(nodes)
					}).catch(err => {
						console.log(err)
					});
			},
			//选择分类后加载属性列表
			onCatalogChange(value, selectedData) {
				//保存当前选择的分类对象
				catalogObjs = selectedData;

				console.log('value: ' + value);
				if (value == '') {
					//清除所有数据
					this.normalData=[]
					this.specData=[]
					this.collapseValue = ''
					return
				}

				let cids = new String(value).split(',');
				if (cids.length > 0) {
					let cid = cids[cids.length - 1];
					console.log(cid);
					let condition = {'cid': cid};
					//加载普通属性
					condition.type = 1;
					this.loadNormal(condition);
					//加载规格属性
					this.loadSpec({'cid': catalogObjs[catalogObjs.length - 1].value, 'type': 2});
					//打开普通属性面板
					this.collapseValue = 1
				}
			},

			//添加属性
			onAddClick(type) {
				//提示选择分类
				if (catalogObjs.length < 1) {
					this.$Message.error('请选择商品分类');
					return;
				}
				//初始化表单数据
				this.formData = {
					id: 0,
					name: '',
					type: '',
					inputType: '',
					required: ''
				};
				//打开添加窗口
				this.initDialog('add', type);
			},

			//初始化窗口
			initDialog(action, type) {
				//显示
				this.show = true;
				//初始化对话框，异步刷新dom
				this.$nextTick(function() {
					//隐藏底部对话框
					this.$refs["attrModal"].footerHide = true;
				});
				//获取分类信息
				let catalog_title = [];
				for (let index in catalogObjs) {
					catalog_title.push(catalogObjs[index].label);
				};
				catalog_title = catalog_title.join(' >> ');
				if (action == 'add') {
					//弹出添加属性的界面
					if (type == 1) {
						this.modalTitle = '添加普通属性';
					} else if (type == 2) {
						this.modalTitle = '添加规格属性';
					}
					this.formType = 'add';
				} else if (action == 'update') {
					if (type == 1) {
						this.modalTitle = '修改普通属性';
					} else if (type == 2) {
						this.modalTitle = '修改规格属性';
					}
					this.formType = 'update';
				}
				this.formData.type = type;
				this.modalTitle = this.modalTitle.concat("：", catalog_title);
				console.log(this.modalTitle);
			},
			//提交表单
			handleSubmit(name) {
				this.$refs[name].validate((valid) => {
					if (valid) {
						if (this.formType == 'add') {
							//添加属性
							addAttribute({
									cid: catalogObjs[catalogObjs.length - 1].value,
									name: this.formData.name,
									type: this.formData.type,
									inputType: this.formData.inputType,
									required: this.formData.required
								})
								.then(res => {
									if (res.data.data.status.code == 2000) {
										//刷新数据
										if (this.formData.type == 1) {
											this.loadNormal({'cid': catalogObjs[catalogObjs.length - 1].value, 'type': 1});
										} else if (this.formData.type == 2) {
											this.loadSpec({'cid': catalogObjs[catalogObjs.length - 1].value, 'type': 2});
										}
										this.$Message.success('添加属性成功!');
									} else {
										this.$Message.error('添加属性失败!');
									}
								})
								.catch(function(error) {
									console.log(error);
								});
						} else if (this.formType == 'update') {
							//修改分类
							updateCatalog({
									id: this.formData.id,
									name: this.formData.name,
									order1: this.formData.order1,
									code: this.formData.code
								})
								.then(res => {
									if (res.data.data.status.code == 2000) {
										this.$Message.success('修改分类成功!');
									} else {
										this.$Message.error('修改分类失败!');
									}
								})
								.catch(function(error) {
									console.log(error);
								});
						}

					} else {
						this.$Message.error('表单数据不合法!');
					}
				})
			},
			//关闭窗口
			handleReset(name) {
				this.show = false;
			},
			//单击查询商品规格属性
			onQueryClick() {
				if (catalogObjs.length == 0) {
					this.$Message.error('没有选择分类')
					return
				}
				//加载规格属性
				this.loadSpec({'cid': catalogObjs[catalogObjs.length - 1].value, 'type': 2});
			}
		}
	}
</script>
